package com.wzq.factory;

import com.wzq.annotation.WzqAutowired;
import com.wzq.annotation.WzqService;
import com.wzq.proxy.CglibProxy;
import com.wzq.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author wzq.Jolin
 * @company none
 * @create 2020-07-01 14:28
 */
@WzqService("proxyFactory")
public class ProxyFactory {

    @WzqAutowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }


    /**
     * Jdk动态代理
     * @param obj  委托对象
     * @return   代理对象
     */
    public Object getJdkProxy(Object obj) {


        return Proxy.newProxyInstance( obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Object result = null;
                        try {
                            // 开启事务(关闭事务的自动提交)
                            transactionManager.beginTransaction();
                            result = method.invoke( obj, args );
                            // 提交事务
                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 回滚事务
                            transactionManager.rollback();
                            // 抛出异常便于上层servlet捕获
                            throw e;

                        }

                        return result;
                    }
                } );
    }



    /**
     * cglib动态代理生成代理对象
     * @param obj 委托对象
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(),new CglibProxy(obj,transactionManager));
    }

}
